package com.czm.art_light.service.impl;

import com.czm.art_light.config.MinioProp;
import com.czm.art_light.config.WxConfig;
import com.czm.art_light.constant.ArtErrorCodeEnum;
import com.czm.art_light.constant.SystemConfigConsts;
import com.czm.art_light.entity.ArtUser;
import com.czm.art_light.exception.BusinessException;
import com.czm.art_light.mapper.ArtUserMapper;
import com.czm.art_light.param.request.ArtUserReqDto;
import com.czm.art_light.param.request.LoginReqDto;
import com.czm.art_light.param.response.ArtLoginRespDto;
import com.czm.art_light.param.response.RestResp;
import com.czm.art_light.param.response.UserBasicInfoRespDto;
import com.czm.art_light.service.ArtUserService;
import com.czm.art_light.service.WxService;
import com.czm.art_light.util.JwtUtils;
import com.czm.art_light.util.MinIoUtil;
import com.czm.art_light.util.UserHolderUtility;
import io.minio.MinioClient;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 用户信息 服务类
 */
@Service
public class ArtUserServiceImpl implements ArtUserService {
    @Autowired
    private ArtUserMapper artUserMapper;

    @Autowired
    private WxService wxService;

    @Autowired
    private MinioProp minioProp;

    @Autowired
    private MinioClient minioClient;

    /**
     * 获取用户的登录请求信息，根据code获取openid
     * 再根据openid获取用户是否注册
     * 如果未注册，则进行注册并且进行登录（生成token 和用户的一些基本信息)
     */
    @Override
    public RestResp<ArtLoginRespDto> login(LoginReqDto loginReqDto) {
        //获取用户的信息，根据code获取openid
        String code = loginReqDto.getCode();
        String openId = wxService.getWxOpenId(code);

        //根据openid 获取用户是否注册
        ArtUser artUser = artUserMapper.getByOpenid(openId);
        //用户未注册
        if (artUser == null) {
            //将微信头像的照片存入minio中
            String avatarUrl = loginReqDto.getAvatarUrl();
            String imageUrl = MinIoUtil.uploadImage(avatarUrl,minioProp.getBucketName(),minioClient);
            //文件上传失败
            if(imageUrl == null) {
                throw new BusinessException(ArtErrorCodeEnum.USER_UPLOAD_FILE_ERROR);
            }
            // 注册(也就是将用户的数据插入到数据库中)
            // 获取昵称
            String nickName = loginReqDto.getNickName();
            artUser = ArtUser.builder()
                   .openId(openId)
                   .nickName(nickName)
                   .avatarUrl(imageUrl)
                   .build();
            artUserMapper.insert(artUser);

            //再次根据openid进行查询
            artUser = artUserMapper.getByOpenid(openId);
            // 若查询结果为空，说明数据插入失败
            if(artUser == null){
                //删除上传成功的图片
                MinIoUtil.deleteFile(minioProp.getBucketName(),imageUrl,minioClient);
                throw new BusinessException(ArtErrorCodeEnum.USER_CREATE_FAILED);
            }
        }
        // 生成token
        String token = JwtUtils.generateToken(artUser.getId(), SystemConfigConsts.FRONT_WX_LOGIN_FLAG);
        // 封装返回的数据
        return RestResp.ok(ArtLoginRespDto.builder()
                        .token(token)
                        .userInfo(UserBasicInfoRespDto.builder()
                                // 用户id
                                .id(artUser.getId())
                                // 用户昵称
                                .nickName(artUser.getNickName())
                                //用户的头像URL
                                .avatarUrl(artUser.getAvatarUrl())
                                .build())
                .build());
    }

    /**
     * 修改用户的信息
     */
    @Override
    public RestResp<Void> updateUser(ArtUserReqDto artUserReqDto) {
        // 获取用户id
        Integer userId = UserHolderUtility.getUserId();
        artUserReqDto.setId(userId);
        artUserMapper.updateById(artUserReqDto);
        return RestResp.ok();
    }
}
